<template>
  <el-dialog
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :title="parameter.title"
    :destroy-on-close="true"
    :append-to-body="true"
    :width="parameter.width"
    :top="parameter.top"
    draggable
  >
    <ProTable
      ref="proTable"
      height="50vh"
      :tool-button="parameter.toolButton"
      :columns="parameter.columns"
      :row-key="parameter.rowKey"
      :request-api="parameter.getTableList"
      :init-param="parameter.initParam"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" :loading="butLoading" @click="handleSubmit">确认</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="FormDialog">
import { ElMessage } from 'element-plus'
import { ProTableInstance, ColumnProps } from '@/components/ProTable/interface'

export interface DialogProps {
  title?: string // 标题
  width?: number // 弹框宽度
  top?: string // 离顶部距离
  toolButton?: boolean
  initParam?: any // 初始化参数
  apiParam?: (params?: any) => any
  rowKey?: string
  api?: (params: any) => Promise<any> // 表单提交api
  columns?: ColumnProps[] // 动态表单字段
  getTableList?: (params: any) => Promise<any> // 获取表格数据的Api
  backTableList?: (params: any) => Promise<any> // 返回主表表格数据的Api
}
// dialog状态
const dialogVisible = ref(false)
const butLoading = ref(false)
// 接受父组件参数，配置默认值
// const parameter = ref<TableParameterProps>({
//   title: '',
//   width: 600,
//   top: '5vh',
//   toolButton: false,
//   columns: [] as ColumnProps[]
// })
let parameter = withDefaults(defineProps<DialogProps>(), {
  title: '',
  width: 600,
  top: '10vh',
  rowKey: 'id',
  toolButton: false,
  initParam: {},
  columns: () => []
})
// ProTable 实例
const proTable = ref<ProTableInstance>()
// 定义 emit 事件
const emit = defineEmits<{
  submitForm: []
}>()
// 表单提交校验
const handleSubmit = () => {
  butLoading.value = true
  if (!proTable.value?.selectedList.length) {
    ElMessage.warning('请选择数据')
    butLoading.value = false
    return
  }
  let paramObj: any = undefined
  let params: any[] | undefined = []
  if (parameter.apiParam) {
    paramObj = parameter.apiParam(proTable.value?.selectedList)
  } else {
    params = proTable.value?.selectedList.map(item => item[parameter.rowKey])
  }
  parameter.api!(paramObj || params).then(res => {
    if (res.code == 200) {
      ElMessage.success('操作成功')
      dialogVisible.value = false
      emit('submitForm')
    } else {
      console.log('message', res.message)
    }
  })
  butLoading.value = false
}

// 取消按钮，重置表单，关闭弹框
const handleCancel = () => {
  butLoading.value = false
  dialogVisible.value = false
}

// 接收父组件参数
const openDialog = (params: DialogProps) => {
  parameter = { ...parameter, ...params }
  butLoading.value = false
  dialogVisible.value = true
}

defineExpose({
  openDialog,
  proTable,
  handleCancel
})
</script>
<style scoped lang="scss"></style>
